﻿// Controllers/AccountController.cs
using System;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Carpool1.Models;
using System.Data.Entity;

namespace Carpool1.Controllers
{
    public class AccountController : Controller
    {
        private readonly CarpoolEntities db = new CarpoolEntities();



        // 登录页面 - GET
        public ActionResult Login(string registered = null)
        {
            if (!string.IsNullOrEmpty(registered))
                ViewBag.SuccessMessage = "注册成功，请登录";

            // 读取记住的手机号
            if (Request.Cookies["PhoneNumber"] != null)
                ViewBag.RememberPhone = Request.Cookies["PhoneNumber"].Value;

            Session.Clear();
            return View();
        }

        // 登录验证 - POST（明文密码验证）
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Login(string phone, string password, bool rememberMe = false)
        {
            if (string.IsNullOrEmpty(phone) || string.IsNullOrEmpty(password))
            {
                ModelState.AddModelError("", "请输入手机号和密码");
                return View();
            }

            try
            {
                // 1. 查询用户（按手机号）
                var user = await db.User.FirstOrDefaultAsync(u => u.PhoneNumber == phone);
                if (user == null)
                {
                    ModelState.AddModelError("", "手机号未注册");
                    return View();
                }

                // 2. 明文密码对比（临时逻辑）
                if (user.Password != password)
                {
                    ModelState.AddModelError("", "密码错误");
                    ViewBag.RememberPhone = phone;
                    return View();
                }

                // 3. 登录成功：记录 Session
                Session["UserID"] = user.UserID;
                Session["UserType"] = user.UserType;
                Session["PhoneNumber"] = user.PhoneNumber;

                // 记住手机号（Cookie）
                if (rememberMe)
                {
                    Response.Cookies["PhoneNumber"].Value = phone;
                    Response.Cookies["PhoneNumber"].Expires = DateTime.Now.AddDays(7);
                }

                return RedirectToAction("Index", "Home");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", "登录失败，请重试");
                return View();
            }
        }

        // 注册页面 - GET
        public ActionResult Register()
        {
            Session.Remove("SmsCode");
            Session.Remove("SmsCodeExpiry");
            return View(new Carpool1.Models.User());
        }

        // 注册提交 - POST（明文密码存储）
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(User model, string verifyCode, string confirmPassword)
        {
            // 验证两次密码一致
            if (model.Password != confirmPassword)
            {
                ModelState.AddModelError("", "两次密码不一致");
                return View(model);
            }

            // 验证码逻辑（如果需要，自行补充短信接口）
            if (Session["SmsCode"] == null || DateTime.Now > (DateTime)Session["SmsCodeExpiry"] || verifyCode != Session["SmsCode"].ToString())
            {
                ModelState.AddModelError("", "验证码错误或已过期");
                return View(model);
            }

            if (ModelState.IsValid)
            {
                // 检查手机号是否已注册
                if (await db.User.AnyAsync(u => u.PhoneNumber == model.PhoneNumber))
                {
                    ModelState.AddModelError("", "该手机号已注册");
                    return View(model);
                }

                // 【明文存储密码】（临时逻辑，正式环境需哈希）
                model.UserType = string.IsNullOrEmpty(Request.Form["userType"]) ? (byte)2 : byte.Parse(Request.Form["userType"]); // 2=乘客（默认）

                db.User.Add(model);
                await db.SaveChangesAsync();

                // 清除验证码
                Session.Remove("SmsCode");
                return RedirectToAction("Login", new { registered = "true" });
            }

            return View(model);
        }

        // 存储验证码（供前端调用）
        [HttpPost]
        public ActionResult StoreSmsCode(string smsCode)
        {
            Session["SmsCode"] = smsCode;
            Session["SmsCodeExpiry"] = DateTime.Now.AddMinutes(5);
            return Json(new { success = true });
        }

        // 退出登录
        public ActionResult Logout()
        {
            Session.Clear();
            Response.Cookies["PhoneNumber"].Expires = DateTime.Now.AddDays(-1);
            return RedirectToAction("Login");
        }
    }
}
